package org.jeecg.modules.yfRepair.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.workflow.service.WorkFlowService;
import org.jeecg.modules.workflow.utils.ProcessKit;
import org.jeecg.modules.yingfWeixgsWeixry.entity.HqYingfWeixgsWeixry;
import org.jeecg.modules.yingfWeixgsWeixry.service.IHqYingfWeixgsWeixryService;
import org.jeecg.modules.zhaojd.entity.HqZhaojd;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.yfRepair.entity.HqYfRepairPiece;
import org.jeecg.modules.yfRepair.entity.HqYfRepair;
import org.jeecg.modules.yfRepair.vo.HqYfRepairPage;
import org.jeecg.modules.yfRepair.service.IHqYfRepairService;
import org.jeecg.modules.yfRepair.service.IHqYfRepairPieceService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 营房报修
 * @Author: jeecg-boot
 * @Date: 2020-06-13
 * @Version: V1.0
 */
@Api(tags = "营房报修")
@RestController
@RequestMapping("/yfRepair/hqYfRepair")
@Slf4j
public class HqYfRepairController {
    @Autowired
    private IHqYfRepairService hqYfRepairService;
    @Autowired
    private IHqYfRepairPieceService hqYfRepairPieceService;
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private IHqYingfWeixgsWeixryService hqYingfWeixgsWeixryService;

    // 查询指定维修公司下的维修员
    @GetMapping(value = "/weixryList")
    public Result<?> weixryList(String weixgs) {
        List list = hqYingfWeixgsWeixryService.list(new QueryWrapper<HqYingfWeixgsWeixry>()
                .eq("weixgs", weixgs)
                .eq("shifpdy", 2));

        IPage<HqYingfWeixgsWeixry> pageList = new Page<>();
        pageList.setRecords(list);
        return Result.ok(pageList);
    }

    @GetMapping(value = "/reStart")
    public Result<?> reStart(String processInstanceId, String taskId) {
        try {
            hqYfRepairService.complateTask(taskId, processInstanceId, 1, "重新提交", null, null);

        } catch (Exception error) {
            return Result.error(error.toString());
        }
        return Result.ok();
    }

    // 指派维修公司或者驳回工单
    @PostMapping(value = "/assignWeixgs")
    public Result<?> assignWeixgs(@RequestBody Map params) {
        // 驳回
        if(params.get("auditStatus").equals(0)) {
            hqYfRepairService.complateTask((String) params.get("taskId"), (String) params.get("processInstanceId"), (Integer) params.get("auditStatus"), (String) params.get("auditMemo"), null, null);
            return Result.ok("驳回成功");
        }
//        营房报修对象
        HqYfRepair hqYfRepair = hqYfRepairService.getById(params.get("id") + "");
        if(hqYfRepair != null) {
            hqYfRepair.setGuisfl(params.get("guisfl") + "");
//            维修公司id
            hqYfRepair.setWeixgsId(params.get("weixgsId") + "");

            // 通过公司id，是否派单员来 查询维修公司派单员
            HqYingfWeixgsWeixry hqYingfWeixgsWeixry = hqYingfWeixgsWeixryService.getOne(new QueryWrapper<HqYingfWeixgsWeixry>()
                    .eq("weixgs", params.get("weixgsId"))
                    .eq("shifpdy", 1), false);
            if(hqYingfWeixgsWeixry == null)
                return Result.error("查询维修公司派单员失败");

            if(hqYfRepairService.updateById(hqYfRepair)) {
                hqYfRepairService.complateTask((String) params.get("taskId"), (String) params.get("processInstanceId"),
                        (Integer) params.get("auditStatus"), (String) params.get("auditMemo"),
                        hqYingfWeixgsWeixry.getWeixry(), hqYfRepair.getWeixryId());

                return Result.ok("操作成功");
            }
            else
                return Result.error("操作失败");
        }
        else
            return Result.error("操作失败");
    }

    // 用户评价，结束流程
    @PostMapping(value = "/kehuPingJia")
    public Result<?> kehuPingJia(@RequestBody Map params) {
        HqYfRepair hqYfRepair = hqYfRepairService.getById(params.get("id") + "");
        if(hqYfRepair != null) {
            hqYfRepair.setWeixzt("4");
            hqYfRepair.setPingf(Integer.parseInt(params.get("pingf") == null ? "0" : params.get("pingf") + ""));

            if(hqYfRepairService.updateById(hqYfRepair)) {
                // 不能驳回
                hqYfRepairService.complateTask((String) params.get("taskId"), (String) params.get("processInstanceId"), 1, (String) params.get("auditMemo"), null, null);
                return Result.ok("操作成功");
            }
            else
                return Result.error("操作失败");
        }
        else
            return Result.error("操作失败");
    }

    // 工人完成维修，有可能修不了。把单退回去，让管理员重新分配
    @PostMapping(value = "/finishRepair")
    public Result<?> finishRepair(@RequestBody Map params) {
        HqYfRepair hqYfRepair = hqYfRepairService.getById(params.get("id") + "");
        if(hqYfRepair != null) {
            hqYfRepair.setFinishTime(new Date());
            hqYfRepair.setWeixzt("3");
            if(hqYfRepairService.updateById(hqYfRepair)) {
                hqYfRepairService.complateTask((String) params.get("taskId"), (String) params.get("processInstanceId"), Integer.parseInt(params.get("auditStatus") + ""), (String) params.get("auditMemo"), null, null);
                return Result.ok("操作成功");
            }
            else
                return Result.error("操作失败");
        }
        else
            return Result.error("操作失败");
    }

    // 分配维修人员或者驳回
    @PostMapping(value = "/assignWeixry")
    public Result<?> assignWeixry(@RequestBody Map params) {
        HqYfRepair hqYfRepair = hqYfRepairService.getById(params.get("id") + "");
        if(hqYfRepair != null) {
            hqYfRepair.setAssignTime(new Date());
            hqYfRepair.setWeixryId(params.get("weixry") + "");
            hqYfRepair.setWeixzt("2");
            if(hqYfRepairService.updateById(hqYfRepair)) {
                hqYfRepairService.complateTask((String) params.get("taskId"), (String) params.get("processInstanceId"),
                        (Integer) params.get("auditStatus"), (String) params.get("auditMemo"), null, hqYfRepair.getWeixryId());
                return Result.ok("操作成功");
            }
            else
                return Result.error("操作失败");
        }
        else
            return Result.error("操作失败");
    }

    // 我的发起
    @GetMapping(value = "/myapplylist")
    public Result<?> myApplyList(HqYfRepair hqYfRepair,
                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 HttpServletRequest req) {
        Page<HqYfRepair> page = new Page<>(pageNo, pageSize);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        IPage<HqYfRepair> iPage = hqYfRepairService.myApplyList(page, user, hqYfRepair);
        if (iPage.getTotal() > 0) {
            iPage.getRecords().forEach(record -> {
                if (null != record.getEndTime()) {
                    record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
                } else {
                    if (null != record.getAuditStatus()) {
                        record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
                    } else {
                        record.setProcessStatus(ProcessKit.FLOW_STATUS_NOT_SUBMIT);
                    }
                }
            });
        }

        return Result.ok(iPage);
    }

    @GetMapping(value = "/mytodolist")
    public Result<?> myTodoList(HqYfRepair hqYfRepair,
                                @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                HttpServletRequest req) {
        Page<HqYfRepair> page = new Page<HqYfRepair>(pageNo, pageSize);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        IPage<HqYfRepair> iPage = hqYfRepairService.myTodoTasks(page,user,hqYfRepair);
        return Result.ok(iPage);
    }

    @GetMapping(value = "/mydonelist")
    public Result<?> myDoneList(HqYfRepair hqYfRepair,
                                @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                HttpServletRequest req) {
        Page<HqYfRepair> page = new Page<HqYfRepair>(pageNo, pageSize);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        IPage<HqYfRepair> iPage = hqYfRepairService.myDoneTasks(page,user,hqYfRepair);
        if(iPage.getTotal()>0){
            iPage.getRecords().forEach(record->{
                if(null != record.getEndTime()){
                    record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
                }else {
                    record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
                }
            });
        }
        return Result.ok(page);
    }

    /**
     * 分页列表查询
     *
     * @param hqYfRepair
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "营房报修-分页列表查询")
    @ApiOperation(value = "营房报修-分页列表查询", notes = "营房报修-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(HqYfRepair hqYfRepair,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<HqYfRepair> queryWrapper = QueryGenerator.initQueryWrapper(hqYfRepair, req.getParameterMap());
        Page<HqYfRepair> page = new Page<HqYfRepair>(pageNo, pageSize);
        IPage<HqYfRepair> pageList = hqYfRepairService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param hqYfRepairPage
     * @return
     */
    @AutoLog(value = "营房报修-添加")
    @ApiOperation(value = "营房报修-添加", notes = "营房报修-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody HqYfRepairPage hqYfRepairPage) {
        HqYfRepair hqYfRepair = new HqYfRepair();
        BeanUtils.copyProperties(hqYfRepairPage, hqYfRepair);

        hqYfRepair.setChuanswczt("0");

        hqYfRepairService.saveMain(hqYfRepair, hqYfRepairPage.getHqYfRepairPieceList());

        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        hqYfRepairService.startFlow(hqYfRepair, loginUser);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param hqYfRepairPage
     * @return
     */
    @AutoLog(value = "营房报修-编辑")
    @ApiOperation(value = "营房报修-编辑", notes = "营房报修-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody HqYfRepairPage hqYfRepairPage) {
        if(StringUtils.equals("用户发起报修",hqYfRepairPage.getTaskName())) {
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            hqYfRepairService.applyAgain(hqYfRepairPage, loginUser);

        } else {
            HqYfRepair hqYfRepair = new HqYfRepair();
            BeanUtils.copyProperties(hqYfRepairPage, hqYfRepair);
            HqYfRepair hqYfRepairEntity = hqYfRepairService.getById(hqYfRepair.getId());
            if (hqYfRepairEntity == null) {
                return Result.error("未找到对应数据");
            }
            hqYfRepairService.updateMain(hqYfRepair, hqYfRepairPage.getHqYfRepairPieceList());
        }
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "营房报修-通过id删除")
    @ApiOperation(value = "营房报修-通过id删除", notes = "营房报修-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        hqYfRepairService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "营房报修-批量删除")
    @ApiOperation(value = "营房报修-批量删除", notes = "营房报修-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.hqYfRepairService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "营房报修-通过id查询")
    @ApiOperation(value = "营房报修-通过id查询", notes = "营房报修-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        HqYfRepair hqYfRepair = hqYfRepairService.getById(id);
        if (hqYfRepair == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(hqYfRepair);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "维修配件通过主表ID查询")
    @ApiOperation(value = "维修配件主表ID查询", notes = "维修配件-通主表ID查询")
    @GetMapping(value = "/queryHqYfRepairPieceByMainId")
    public Result<?> queryHqYfRepairPieceListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<HqYfRepairPiece> hqYfRepairPieceList = hqYfRepairPieceService.selectByMainId(id);
        return Result.ok(hqYfRepairPieceList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param hqYfRepair
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HqYfRepair hqYfRepair) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<HqYfRepair> queryWrapper = QueryGenerator.initQueryWrapper(hqYfRepair, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //Step.2 获取导出数据
        List<HqYfRepair> queryList = hqYfRepairService.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<HqYfRepair> hqYfRepairList = new ArrayList<HqYfRepair>();
        if (oConvertUtils.isEmpty(selections)) {
            hqYfRepairList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            hqYfRepairList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<HqYfRepairPage> pageList = new ArrayList<HqYfRepairPage>();
        for (HqYfRepair main : hqYfRepairList) {
            HqYfRepairPage vo = new HqYfRepairPage();
            BeanUtils.copyProperties(main, vo);
            List<HqYfRepairPiece> hqYfRepairPieceList = hqYfRepairPieceService.selectByMainId(main.getId());
            vo.setHqYfRepairPieceList(hqYfRepairPieceList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "营房报修列表");
        mv.addObject(NormalExcelConstants.CLASS, HqYfRepairPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("营房报修数据", "导出人:" + sysUser.getRealname(), "营房报修"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<HqYfRepairPage> list = ExcelImportUtil.importExcel(file.getInputStream(), HqYfRepairPage.class, params);
                for (HqYfRepairPage page : list) {
                    HqYfRepair po = new HqYfRepair();
                    BeanUtils.copyProperties(page, po);
                    hqYfRepairService.saveMain(po, page.getHqYfRepairPieceList());
                }
                return Result.ok("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

}
